package com.art8173.service.impl;

import com.art8173.exception.ClazzException;
import com.art8173.mapper.ClazzMapper;
import com.art8173.pojo.Clazz;
import com.art8173.pojo.ClazzQueryParam;
import com.art8173.pojo.Emp;
import com.art8173.pojo.PageResult;
import com.art8173.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        //1. 设置PageHelper分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        //2. 执行查询
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);
        clazzList.forEach(clazz -> {
//            - 当前时间 > 结课时间：状态未 已结课。
//            - 当前时间 < 开课时间：状态未 未开班。
//            - 否则，就是 在读中。
            clazz.setStatus(clazz.getEndDate().isBefore(LocalDate.now()) ? "已结课" : clazz.getBeginDate().isAfter(LocalDate.now()) ? "未开班" : "在读中");

        });
        //3. 封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteByIds(Integer id) {
        // 检查该班级下是否关联有学生
        Integer studentCount = clazzMapper.countStudentsByClazzId(id);

        // 如果有关联的学生，则不允许删除
        if (studentCount > 0) {
            throw new ClazzException(ClazzException.CLAZZ_HAS_STUDENTS);
        }
        clazzMapper.deleteByIds(id);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }
}
